package com.work.formaldehyde.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.lljjcoder.style.citylist.CityListSelectActivity;
import com.lljjcoder.style.citylist.bean.CityInfoBean;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.CityCheckAdapter;
import com.work.formaldehyde.activityadapter.CityCheckGirdAdapter;
import com.work.formaldehyde.activityadapter.CityManageAdapter;
import com.work.formaldehyde.homefragment.TianqiFragment;
import com.work.formaldehyde.model.JsonBean;
import com.work.formaldehyde.model.KePuBanner;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.GetJsonDataUtil;
import com.work.formaldehyde.util.Url;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class CityCheckActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private boolean ok = true;

    private RelativeLayout check_text, hotcity;
    private TextView closeview;
    private EditText edit_city;
    public static ListView city_check_list;
    private CityCheckAdapter myAdapter;
    private GridView hot_grid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 0);
        setContentView(R.layout.activity_checkcity);
        check_text = findViewById(R.id.check_text);
        check_text.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(CityCheckActivity.this))
            inti();
    }

    public static SQLiteDatabase database;
    public static ArrayList<String> new_list_view;
    public static ArrayList<String> new_list_views;
    private CityCheckGirdAdapter myAdapters;

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 初始加载热门视图
     */
    public void Init() {
        new_list_views = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            new_list_views.add("" + i);
        }
        myAdapters = new CityCheckGirdAdapter(new_list_views,
                CityCheckActivity.this, ok);
        hot_grid.setAdapter(myAdapters);
    }


    /**
     * 初始化加载调用方法
     */
    public void inti() {
        initJsonData();
        File file = new File(this.getFilesDir(), ApiUtils.DB_NAME);
        database = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
        closeview = findViewById(R.id.closeview);
        city_check_list = findViewById(R.id.city_check_list);
        new_list_view = new ArrayList<>();
        city_check_list.setOnItemClickListener(this);
        edit_city = findViewById(R.id.edit_city);
        edit_city.setFocusable(false);
        edit_city.setFocusableInTouchMode(false);
        edit_city.setOnClickListener(this);
        hotcity = findViewById(R.id.hotcity);
        hot_grid = findViewById(R.id.hot_grid);
        Init();
        edit_city.clearFocus();
        edit_city.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                /*判断是否是“GO”键*/
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    String keytag = edit_city.getText().toString().trim();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    boolean isOpen = imm.isActive();
                    if (new_list_view.size() > 0)
                        new_list_view.clear();
                    if (isOpen)
                        imm.hideSoftInputFromWindow(edit_city.getWindowToken(), 0);
                    String gettext = SelectCity(edit_city.getText().toString());
                    ApiUtils.SetToast(CityCheckActivity.this, gettext);
                    //做查找请求
                    return true;
                }
                return false;
            }
        });
        edit_city.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String GetToString = edit_city.getText().toString();
                if (GetToString.equals("")) {
                    ok = true;
                    closeview.setText(R.string.close);
                    hot_grid.setVisibility(View.VISIBLE);
                    hotcity.setVisibility(View.VISIBLE);
                    city_check_list.setVisibility(View.GONE);

                } else {
                    ok = false;
                    closeview.setText(R.string.check);
                    new_list_view.clear();
                    hot_grid.setVisibility(View.GONE);
                    hotcity.setVisibility(View.GONE);
                    city_check_list.setVisibility(View.VISIBLE);

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CityListSelectActivity.CITY_SELECT_RESULT_FRAG) {
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    return;
                }
                Bundle bundle = data.getExtras();
                CityInfoBean cityInfoBean = (CityInfoBean) bundle.getParcelable("cityinfo");
                if (null == cityInfoBean) {
                    return;
                }
                ApiUtils.windows(CityCheckActivity.this, check_text, "正在添加");
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                okHttp_postFromParameters1(cityInfoBean.getName());
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.check_text:
                if (ok)
                    onBackPressed();
                else {
                    Intent intent = new Intent(CityCheckActivity.this, CityListSelectActivity.class);
                    startActivityForResult(intent, CityListSelectActivity.CITY_SELECT_RESULT_FRAG);
                    if (new_list_view.size() > 0)
                        new_list_view.clear();
                    String gettext = SelectCitys(edit_city.getText().toString());
                    ApiUtils.SetToast(CityCheckActivity.this, gettext);
                }
                break;
            case R.id.edit_city:
//                    Intent intent = new Intent(CityCheckActivity.this, CityListSelectActivity.class);
//                    startActivityForResult(intent, CityListSelectActivity.CITY_SELECT_RESULT_FRAG);
                if (isLoaded)
                    selectcity();
                else {
                    ApiUtils.SetToast(CityCheckActivity.this, "城市列表初始化中");
                }
                break;
        }
    }

    /**
     * 获取城市的方法(中文)
     *
     * @param ancient 条件查询值
     */
    public String SelectCity(String ancient) {
        Cursor mCursor = database.query("city_old", null, "name=?", new String[]{ancient}, null,
                null, null);
        String getxdw = null;
        while (mCursor.moveToNext()) {
            new_list_view.add(mCursor.getString(1));
        }
        if (new_list_view.size() > 0) {
            myAdapter = new CityCheckAdapter(new_list_view,
                    CityCheckActivity.this, ok);
            city_check_list.setAdapter(myAdapter);
        }
        return getxdw;
    }

    /**
     * 获取城市的方法(拼音)
     *
     * @param ancient 条件查询值
     */
    public String SelectCitys(String ancient) {
        Cursor mCursor = database.query("city_old", null, "pinyin=?", new String[]{ancient}, null,
                null, null);
        String getxdw = null;
        while (mCursor.moveToNext()) {
            new_list_view.add(mCursor.getString(1));
        }
        if (new_list_view.size() > 0) {
            myAdapter = new CityCheckAdapter(new_list_view,
                    CityCheckActivity.this, ok);
            city_check_list.setAdapter(myAdapter);
        }
        return getxdw;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }

    private void okHttp_postFromParameters1(final String city) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder()
                            .add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("city", city).add("remind", "0").build();
                    Request request = new Request.Builder().url(Url.ADDCITY).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        ApiUtils.SetToast(CityCheckActivity.this, success_Object.getString("msg"));
                        TianqiFragment.ischeck = true;
                        onBackPressed();
                    } else {
                        ApiUtils.SetToast(CityCheckActivity.this, success_Object.getString("msg"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void initJsonData() {//解析数据
        String JsonData = new GetJsonDataUtil().getJson(CityCheckActivity.this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }
            options2Items.add(cityList);
            options3Items.add(province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    //  省
    private List<JsonBean> options1Items = new ArrayList<JsonBean>();
    //  市
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    //  区
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void selectcity() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(CityCheckActivity.this, new OnOptionsSelectListener() {
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";
                String tx = opt2tx + opt3tx;
                ApiUtils.SetLog("tx=" + tx);
                ApiUtils.windows(CityCheckActivity.this, check_text, "正在添加");
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                okHttp_postFromParameters1(opt3tx);
            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };
}
